package com.xjs.service.impl;

import com.xjs.constants.FastJsonConvertUtil;
import com.xjs.dao.BrokerMessageLogMapper;
import com.xjs.dao.OrderMapper;
import com.xjs.entity.BrokerMessageLog;
import com.xjs.entity.Order;
import com.xjs.service.RabbitProducerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

import static com.xjs.constants.StaticNumber.*;

@Slf4j
@Component
public class RabbitProducerServiceImpl implements RabbitProducerService{

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private BrokerMessageLogMapper brokerMessageLogMapper;


    /**
     * @Description 发送消息
     * @UserModule: exam-web-paper
     * @param order
     * @return void
     */
    @Override
    public void topicSend(Order order) {
        Date orderTime = new Date();
        orderMapper.insert(order);
        BrokerMessageLog brokerMessageLog = new BrokerMessageLog();
        brokerMessageLog.setMessageId(order.getMessageId());
        brokerMessageLog.setMessage(FastJsonConvertUtil.convertObjectToJSON(order));
        // 设置消息状态为0 表示发送中
        brokerMessageLog.setStatus(IN_DELIVERY);
        // 设置消息未确认超时时间窗口为 一分钟
        brokerMessageLog.setNextRetry(DateUtils.addMinutes(orderTime,1*60000));
        brokerMessageLog.setCreateTime(new Date());
        brokerMessageLog.setUpdateTime(new Date());
        brokerMessageLogMapper.insertSelective(brokerMessageLog);
        //构建回调返回的数据
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(order.getMessageId());
        rabbitTemplate.convertAndSend(TOPIC_EXCHANGE,JAVAYOHO_TOPIC,FastJsonConvertUtil.convertObjectToJSON(order),correlationData);
    }

}
